/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sirtet;

/**
 * A wrapped structure representing an action triggered by a Player and to be
 * processed by a GameBoard or relayed to the network.
 * @author guangwei.zhu
 */
public class GameAction implements Cloneable {

    public String actor;        // Actor ID
    public String command;       // Action flag
    public static final String NOOP = "";

    /**
     * Construct an action by specifying the ID of the initiator and a string
     * indicating the action content
     * @param actor the ID of the triggering player
     * @param action a string representing the action content
     */
    public GameAction(String actor, String action) {

        // Must not contain colon or newline since we use them as separators
        if (actor.contains(":") || action.contains(":") ||
                actor.contains("\n") || action.contains("\n")) {
            throw new IllegalArgumentException();
        }

        this.command = action;
        this.actor = actor;
    }

    /**
     * Construct a blank action (no operation, anonymous ID)
     */
    public GameAction() {
        this.command = NOOP;  // Do nothing
        this.actor = "";
    }

    /**
     * Return the string representation of this action object in the format
     * "ID:CONTENT"
     * @return the string representation
     */
    @Override
    public String toString() {
        // Message format "ACTORID:ACTION"
        String message = actor + ":" + command;
        return message;
    }

    /**
     * Parse a string representation to a TetrisAction object
     * @param data the string that is to be parsed
     * @return the parsed TetrisAction object
     */
    public static GameAction fromString(String data) {

        // Check data format
        if (data.length() - data.replace(":", "").length() != 1) {
            // If the occurrence of colon is not one
            return null;
        }

        // Reconstruct object
        GameAction action = new GameAction();
        String[] strs = data.split(":");

        action.actor = strs[0];
        action.command = strs[1];

        return action;
    }
}
